import axios from "axios";
import { ElMessage } from "element-plus";
import { resetStores } from "@/utils/resetStores";
import router from "@/router/index.ts";

// 配置项
const BaseUrl = import.meta.env.VITE_APP_SERVICE_URL;
const service = axios.create({
  baseURL: BaseUrl || "cy", // 接口地址(环境配置||代理)
  timeout: 5000, // 请求超时时间
});

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    const { url } = config;
    // 请求头加入token
    if (url !== "/login" && url !== "/sign") {
      const token = localStorage.getItem("VUE3-TOKEN");
      if (token) {
        config.headers["Authorization"] = `Bearer ${token}`;
      } else {
        // 取消请求
        config.cancelToken = new axios.CancelToken((cancel) => {
          cancel("token 不存在");
        });
        ElMessage({
          type: "error",
          message: "token 不存在",
        });
      }
    }
    // 处理 multipart/form-data 文件请求
    if (config.data instanceof FormData) {
      // 显式设置 Content-Type（避免浏览器自动生成错误的boundary）
      config.headers["Content-Type"] = "multipart/form-data";
    }
    console.log(config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    console.log(response);
    return response;
  },
  (error) => {
    // 检查是否是请求取消的错误
    if (axios.isCancel(error)) {
      console.warn("请求已取消：", error.message);
      return Promise.resolve(); // 静默处理，不报错
    }
    console.log(error.response);
    let msg = "";
    let status = error.response.status;
    switch (status) {
      case 401:
        msg = "Token无效或已过期";
        resetStores(); //清除仓库
        router.push("/login"); //返回登录
        break;
      case 403:
        msg = "无访问权限";
        break;
      case 404:
        msg = "请求地址错误";
        break;
      case 500:
        msg = "服务器出现问题";
        break;
      default:
        msg = "无网络";
    }
    ElMessage({
      type: "error",
      message: msg,
    });

    return Promise.reject(error);
    // return Promise.resolve(); // 静默处理，不报错
  }
);
export default service;
